/**
 * 
 */
package com.android.myqimc;


import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

/**
 * @author Taohuang
 *
 */
public class Settings extends Activity {

	//上次MC第一天的日期
	private String mcdate_value = "";
	  //MC周期
	  private String period_value = "";
	  //每日提醒时间
	  private String remind_value = "";
	  //声明日期变量
	  private int mYear;
	  private int mMonth;
	  private int mDay;
	  private DatePicker dp_mc;//日期选择控件
	  private EditText txt_periodval;//周期文本输入控件
	  private Button btn_saving;//保存按钮
	  private TimePicker tp_mc;//时间选择控件

	  /** Called when the activity is first created. */
	  @Override
	  public void onCreate(Bundle savedInstanceState)
	  {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.settings);

	    dp_mc = (DatePicker) findViewById(R.id.dp_mc);
	    txt_periodval = (EditText) this.findViewById(R.id.txt_periodval);
	    btn_saving = (Button) this.findViewById(R.id.btn_saving);
	    tp_mc = (TimePicker) findViewById(R.id.tp_mc);

	    Bundle bunde = this.getIntent().getExtras();//从上一个activity获取传递的数据
	    mcdate_value = bunde.getString(MainActivity.mcdate_key);
	    period_value = bunde.getString(MainActivity.period_key);
	    remind_value = bunde.getString(MainActivity.remind_key);

	    //MC周期
	    txt_periodval.setText(period_value);

	    //上次MC第一天的日期设置到DataPicker
	    Calendar calendar = Calendar.getInstance();
	    if (mcdate_value != null)
	    {
	      mYear = Integer.parseInt(mcdate_value.substring(0, 4));
	      mMonth = Integer.parseInt(mcdate_value.substring(4, 6)) - 1;
	      mDay = Integer.parseInt(mcdate_value.substring(6, 8));
	    } else
	    {
	      mYear = calendar.get(Calendar.YEAR);
	      mMonth = calendar.get(Calendar.MONTH);
	      mDay = calendar.get(Calendar.DAY_OF_MONTH);
	    }
	    dp_mc.init(mYear, mMonth, mDay, null);

	    //每日提醒设置到TimePicker
	    if (remind_value != null && remind_value.length() == 4)
	    {
	      tp_mc.setCurrentHour(Integer.parseInt(remind_value
	          .substring(0, 2)));
	      tp_mc.setCurrentMinute(Integer.parseInt(remind_value
	          .substring(2, 4)));
	    }
	    //保存将新的设置值写回文件
	    btn_saving.setOnClickListener(new Button.OnClickListener()
	    {

	      @Override
	      public void onClick(View arg0)
	      {

	        FileOutputStream fos;
	        try
	        {
	          //取得DataPicker的日期
	          int m = dp_mc.getMonth() + 1;
	          String strM = m >= 10 ? "" + m : "0" + m;
	          int d = dp_mc.getDayOfMonth();
	          String strD = d >= 10 ? "" + d : "0" + d;
	          mcdate_value = "" + dp_mc.getYear() + "" + strM
	              + "" + strD;

	          //取得MC周期值
	          period_value = txt_periodval.getText().toString();

	          //取得TimePicker的时间
	          int h = tp_mc.getCurrentHour();
	          String strH = h >= 10 ? "" + h : "0" + h;
	          int mu = tp_mc.getCurrentMinute();
	          String strMu = mu >= 10 ? "" + mu : "0" + mu;
	          remind_value = strH + strMu;

	          fos = openFileOutput(MainActivity.fileName,
	              MODE_WORLD_WRITEABLE);//创建配置文件mc.ini
	          BufferedOutputStream bos = new BufferedOutputStream(fos);//创建文件输出流

	          String txt = MainActivity.mcdate_key + "=" + mcdate_value;
	          bos.write(txt.getBytes());

	          bos.write(new String("\n").getBytes());
	          txt = MainActivity.period_key + "=" + period_value;
	          bos.write(txt.getBytes());

	          bos.write(new String("\n").getBytes());
	          txt = MainActivity.remind_key + "=" + remind_value;
	          bos.write(txt.getBytes());

	          bos.close();
	          fos.close();
	        } catch (FileNotFoundException e)
	        {
	          // TODO Auto-generated catch block
	          e.printStackTrace();
	        } catch (IOException e)
	        {
	          // TODO Auto-generated catch block
	          e.printStackTrace();
	        }

	        Intent receiverIntent = new Intent(Settings.this,
	            AlarmReceiver.class);
	        PendingIntent sender = PendingIntent.getBroadcast(
	        		Settings.this, 1, receiverIntent, 0);
	        //获取AlarmManager服务
	        AlarmManager am;
	        am = (AlarmManager) getSystemService(ALARM_SERVICE);
	        //先将AlarmManager停止
	        am.cancel(sender);

	        //1天的毫秒数
	        int times = 24 * 60 * 60 * 1000;

	        //获取TimePicker的值作为驱动的时间
	        Calendar calendar = Calendar.getInstance();
	        calendar.set(Calendar.HOUR_OF_DAY, tp_mc
	            .getCurrentHour());
	        calendar.set(Calendar.MINUTE, tp_mc
	            .getCurrentMinute());
	        calendar.set(Calendar.SECOND, 0);
	        calendar.set(Calendar.MILLISECOND, 0);

	        long triggerTime = calendar.getTimeInMillis();

	        //每日同一时间运行一次
	        am.setRepeating(AlarmManager.RTC_WAKEUP, triggerTime,
	            times, sender);

	        //回到主界面
	        Intent intent = new Intent();
	        intent.setClass(Settings.this, MainActivity.class);
	        startActivity(intent);
	        finish();
	      }
	    });//end setOnClickListener
	  }
}
